package com.heima.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
全局过滤器，校验token是否有效
 */
@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //1.获取请求实例
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应实例
        ServerHttpResponse response = exchange.getResponse();
        //3.获取请求路径
        String uri = request.getURI().getPath();
        //4.判断是否是登录请求路径,如果是则直接放行
        if (uri.equals("/login")){
            return chain.filter(exchange);
        }
        //5.获取请求头中的信息
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        //6.判断token是否为空,为空则返回401
        if (StringUtils.isBlank(token)){
            log.error("token值为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接结束
            return response.setComplete();
        }

        try {
            //7.不为空则解析token,解析失败则返回401
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken==1||verifyToken==2){
                log.error("token过期");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //直接结束
                return response.setComplete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //直接结束
            return response.setComplete();
        }

        //8.放行
        return chain.filter(exchange);
    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
